package com.googlecode.cannedbeans.mojo;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.artifact.DependencyResolutionRequiredException;

import java.net.URL;
import java.net.URLClassLoader;
import java.net.MalformedURLException;
import java.util.List;
import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: benny
 * Date: Apr 13, 2009
 * Time: 10:45:47 AM
 * @goal generate
 * @requiresDependencyResolution
 */
public class CannedBeansGeneratorMojo extends AbstractMojo {

    /**
     * Classes to look for.
     *
     * @parameter
     * @required
     */
    private String[] classnames;

    /**
     * The maven project.
     * 
     * @parameter expression="${project}"
     * @readonly
     * @required
     */
    private MavenProject project;

    /**
     * Directory to store the canned beans.
     * @parameter
     * @required 
     */
    private File outputdir;

    /**
     * Storage format desired.
     * @parameter
     * @required
     */
    private String outputformat;

    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            getLog().debug("Starting CannedBeans generation.");
            getLog().debug("Project = " + project);
            List<String> compileclasses = project.getRuntimeClasspathElements();

            URL[] urlarray = new URL[compileclasses.size()];
            int i = 0;
            for (String url: compileclasses){
                getLog().info("Classpath element found: " + url);
                urlarray[i++] = new File(url).toURI().toURL();
            }
            
            URLClassLoader classLoader = new URLClassLoader(urlarray);

            for (String classname: classnames){
                Class clazz = Class.forName(classname, true, classLoader);
                doGenerateBeans(clazz);
            }
        } catch (ClassNotFoundException e) {
            throw new MojoFailureException("Class not found", e);
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("DependencyResolution is required." ,e ); 
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("Malformed URL found for loading classes.", e);
        }
    }

    private void doGenerateBeans(Class clazz) {
        //FIXME: stub.
    }

    /*
    Note that plexus uses field injection and does not call these setters.
     */
    public void setClassnames(String[] classnames) {
        this.classnames = classnames;
    }

    public void setProject(MavenProject project) {
        this.project = project;
    }

    public void setOutputdir(File outputdir) {
        this.outputdir = outputdir;
    }

    public void setOutputformat(String outputformat) {
        this.outputformat = outputformat;
    }
}
